import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    // 加载状态
    isLoading: false,
    // 错误信息
    error: null
  }),
  
  getters: {
    // 获取购物车商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },
    // 获取购物车总价
    totalPrice: (state) => {
      return state.items.reduce((total, item) => {
        // 根据选中的规格获取价格
        const selectedPrice = item.selectedSpec?.price || item.price || 0
        return total + selectedPrice * item.quantity
      }, 0)
    },
    // 获取选中的商品
    selectedItems: (state) => {
      return state.items.filter(item => item.selected)
    },
    // 获取选中商品的总价
    selectedTotalPrice: (state) => {
      return state.selectedItems.reduce((total, item) => {
        const selectedPrice = item.selectedSpec?.price || item.price || 0
        return total + selectedPrice * item.quantity
      }, 0)
    }
  },
  
  actions: {
    // 加载购物车数据
    loadCart() {
      this.isLoading = true
      try {
        const savedCart = localStorage.getItem('cart')
        if (savedCart) {
          this.items = JSON.parse(savedCart)
        }
      } catch (error) {
        this.error = '加载购物车失败'
        console.error('加载购物车失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    // 保存购物车数据到本地存储
    saveCart() {
      try {
        localStorage.setItem('cart', JSON.stringify(this.items))
      } catch (error) {
        this.error = '保存购物车失败'
        console.error('保存购物车失败:', error)
      }
    },
    
    // 添加商品到购物车
    addToCart(product, quantity = 1, selectedSpec = null) {
      // 查找是否已存在相同商品和规格
      const existingItemIndex = this.items.findIndex(
        item => item.id === product.id && 
        JSON.stringify(item.selectedSpec) === JSON.stringify(selectedSpec)
      )
      
      if (existingItemIndex !== -1) {
        // 已存在，增加数量
        this.items[existingItemIndex].quantity += quantity
      } else {
        // 不存在，添加新商品
        this.items.push({
          ...product,
          quantity,
          selectedSpec,
          selected: true
        })
      }
      
      this.saveCart()
    },
    
    // 更新商品数量
    updateQuantity(itemId, quantity, specId = null) {
      const itemIndex = this.items.findIndex(
        item => item.id === itemId && 
        (specId === null || JSON.stringify(item.selectedSpec) === JSON.stringify(specId))
      )
      
      if (itemIndex !== -1) {
        if (quantity > 0) {
          this.items[itemIndex].quantity = quantity
        } else {
          // 数量为0或负数，移除商品
          this.removeFromCart(itemId, specId)
          return
        }
        this.saveCart()
      }
    },
    
    // 从购物车移除商品
    removeFromCart(itemId, specId = null) {
      const itemIndex = this.items.findIndex(
        item => item.id === itemId && 
        (specId === null || JSON.stringify(item.selectedSpec) === JSON.stringify(specId))
      )
      
      if (itemIndex !== -1) {
        this.items.splice(itemIndex, 1)
        this.saveCart()
      }
    },
    
    // 切换商品选中状态
    toggleSelect(itemId, specId = null) {
      const itemIndex = this.items.findIndex(
        item => item.id === itemId && 
        (specId === null || JSON.stringify(item.selectedSpec) === JSON.stringify(specId))
      )
      
      if (itemIndex !== -1) {
        this.items[itemIndex].selected = !this.items[itemIndex].selected
        this.saveCart()
      }
    },
    
    // 全选/取消全选
    toggleSelectAll(selectAll) {
      this.items.forEach(item => {
        item.selected = selectAll
      })
      this.saveCart()
    },
    
    // 清空购物车
    clearCart() {
      this.items = []
      this.saveCart()
    },
    
    // 根据选中的商品创建订单
    createOrderFromSelectedItems() {
      const selectedItems = this.selectedItems
      if (selectedItems.length === 0) {
        this.error = '请选择要结算的商品'
        return null
      }
      
      const orderItems = selectedItems.map(item => ({
        id: item.id,
        name: item.name,
        price: item.selectedSpec?.price || item.price,
        quantity: item.quantity,
        image: item.image,
        spec: item.selectedSpec
      }))
      
      const order = {
        id: `order_${Date.now()}`,
        items: orderItems,
        totalAmount: this.selectedTotalPrice,
        totalQuantity: selectedItems.reduce((total, item) => total + item.quantity, 0),
        createTime: new Date().toISOString(),
        status: 'pending'
      }
      
      // 从购物车中移除已结算的商品
      this.items = this.items.filter(item => !item.selected)
      this.saveCart()
      
      return order
    }
  }
})